package neptune.manager.connector;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import neptune.manager.utils.SSHCommandException;
import neptune.manager.utils.SSHConnectionHandler;

/**
 * 
 * @author Luigi Lorenzo Arpino [luigiarpino@yahoo.it]
 * 
 */
public class XenStatistic {

	/**
	 * Ottiene le statistiche sulle macchine virtuali
	 * 
	 * @param ipAddress
	 * @param password
	 * @param sshPort
	 * @return
	 * @throws IOException
	 * @throws SSHCommandException
	 */
	public static String[][] getStatistic(String ipAddress, String password,
			String sshPort) throws IOException, SSHCommandException {
		System.out.print("ssh->" + sshPort);
		int port = Integer.parseInt(sshPort);
		SSHConnectionHandler handler = SSHConnectionHandler
				.createSSHConnectionHandler(ipAddress, port, "root", password);
		handler.sendCommand("xentop -b -i 2 -d 1");
		BufferedReader reader = handler.getStdOut();
		String linea;
		String contenuto = new String();
		boolean isFirstLineRead = false;
		ArrayList<String[]> tmp = new ArrayList<String[]>(0);
		while ((linea = reader.readLine()) != null) {
			if (linea.contains("NAME") && linea.contains("STATE")
					&& linea.contains("CPU(sec)"))
				break;
		}
		while ((linea = reader.readLine()) != null) {
			if (linea.contains("NAME") && linea.contains("STATE")
					&& linea.contains("CPU(sec)")) {
				isFirstLineRead = true;
			} else if (isFirstLineRead) {
				contenuto += "\n" + linea;
				StringTokenizer st = new StringTokenizer(linea);
				String nome = st.nextToken();
				String stato = st.nextToken();
				String cpuSec = st.nextToken();
				String cpuPerc = st.nextToken();
				if (Double.valueOf(cpuPerc).doubleValue() > 100)
					cpuPerc = "100";
				String memK = String.valueOf(Integer.valueOf(st.nextToken())
						.intValue() / 1024);
				String memPerc = st.nextToken();
				String maxMemK = st.nextToken();
				if (maxMemK.equalsIgnoreCase("no")) {
					maxMemK += " " + st.nextToken();
				} else {
					maxMemK = String.valueOf(Integer.valueOf(maxMemK)
							.intValue() / 1024);
				}
				String maxMemPerc = st.nextToken();
				String vcpus = st.nextToken();
				tmp.add(new String[] { nome, stato, cpuSec, cpuPerc, memK,
						memPerc, maxMemK, maxMemPerc, vcpus });
			}
		}
		handler.dispose();

		return tmp.toArray(new String[][] {});

	}

	public static void main(String[] args) {
		if (Double.valueOf("101.0").doubleValue() > 100)
			System.out.print("Ola");
	}

}